package com.kinon.ycjshop.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.ycjshop.Constatus;
import com.kinon.ycjshop.R;
import com.kinon.ycjshop.data.DataModel;
import com.kinon.ycjshop.data.UPacketFactory;
import com.kinon.ycjshop.service.GetMakemealService;
import com.kinon.ycjshop.tools.HttpTools;
import com.kinon.ycjshop.tools.NetWorkUtil;
import com.kinon.ycjshop.tools.SPManage;
import com.kinon.ycjshop.tools.SharedPreferencesUtil;
import com.kinon.ycjshop.tools.Url;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.ICheckFileCallback;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.ISendCallback;
import sunmi.ds.data.DataPacket;


public class LoginActivity extends Activity implements OnClickListener {

    private static final String SHOW_IMG_LIST_ID = "SHOW_IMG_LIST_ID";
    private static final String WELCOME_IMG_ID = "WELCOME_IMG_ID";
    private final static String SHOW_VIDEO_LIST_DATA_ID = "SHOW_VIDEO_LIST_DATA_ID";
    private final static String SHOW_IMGS_LIST_DATA_ID = "SHOW_IMGS_LIST_DATA_ID";
    private static int IS_CURRENT_PAGE = 1;
    long taskId;
    String pathBig = Environment.getExternalStorageDirectory().getPath() + "/dcim/caizhengting.png";
    //    String pathBig ="/data/user/0/com.kinon.market/filpicturees/caizhengting.png";
    DSKernel mDSKernel;// SDK核心类
    DataPacket dsPacket;
    IConnectionCallback mConnCallback = new IConnectionCallback() {// SDK链接状态回调
        @Override
        public void onDisConnect() {
        }

        @Override
        public void onConnected(final ConnState state) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//					Toast.makeText(MainActivity.this, "state:"+state, Toast.LENGTH_LONG).show();
                    switch (state) {
                        case AIDL_CONN:
                            //与本地service的连接畅通
                            break;
                        case VICE_SERVICE_CONN:
                            //与副屏service连接畅通
                            long fileId = SharedPreferencesUtil.getLong(LoginActivity.this, SHOW_IMG_LIST_ID);
                            long fileId1 = SharedPreferencesUtil.getLong(LoginActivity.this, WELCOME_IMG_ID);
                            long fileId2 = SharedPreferencesUtil.getLong(LoginActivity.this, SHOW_VIDEO_LIST_DATA_ID);
                            long fileId3 = SharedPreferencesUtil.getLong(LoginActivity.this, SHOW_IMGS_LIST_DATA_ID);
                            if (fileId2 != -1L) checkImg(fileId2, SHOW_VIDEO_LIST_DATA_ID);
                            if (fileId3 != -1L) checkImg(fileId3, SHOW_IMGS_LIST_DATA_ID);
                            if (fileId != -1L) checkImg(fileId, SHOW_IMG_LIST_ID);
                            if (fileId1 != -1L) checkImg(fileId1, WELCOME_IMG_ID);
                            break;
                        case VICE_APP_CONN:
                            //与副屏app连接畅通
                            break;

                        default:
                            break;
                    }

                }
            });
        }
    };
    /**
     * 登录
     */
    private Button btn_login;
    /**
     * 紧急离线模式
     */
    private Button btn_urgent;
    /**
     * 手机号
     */
    private EditText et_phone;
    /**
     * 密码
     */
    private EditText et_password;
    private String serverUrl = "";
    private int errorNum = 0;
    private long exitTime = 0;

    private LinearLayout ll_input_url;
    private EditText et_input_url;
    private Button btn_yes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        isgetUrl();
        initRes();
        initSDK();
    }

    private void initRes() {
        btn_login = (Button) findViewById(R.id.btn_login);
        et_phone = (EditText) findViewById(R.id.et_name);
        et_password = (EditText) findViewById(R.id.et_pwd);
        btn_urgent = (Button) findViewById(R.id.btn_urgent);
        SharedPreferences spuser = getSharedPreferences("spuser", Context.MODE_PRIVATE);
        if (!"".equals(spuser)) {
            et_phone.setText(spuser.getString("phone", ""));
			et_password.setText(spuser.getString("pwd", ""));
        }
        /**登录*/
        btn_login.setOnClickListener(this);
        btn_urgent.setOnClickListener(this);

        TextView tv_headline = findViewById(R.id.tv_headline);
        tv_headline.setOnClickListener(this);

        ll_input_url = findViewById(R.id.ll_input_url);
        et_input_url = findViewById(R.id.et_input_url);
        btn_yes = findViewById(R.id.btn_yes);
        btn_yes.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.btn_urgent:
                urgentLogin();
                break;
            case R.id.tv_headline:
                // 连续点击3次 显示输入框
                inputUrl();
                break;
            case R.id.btn_yes:
                // 设置URL
                setUrl();
                break;
        }
    }

    /**
     * 手动输入站点
     */
    int count = 0;
    long start = 0;
    long end =0;

    private void inputUrl() {
        count++;
        if (count == 1) {
            start = System.currentTimeMillis();
        }
        if (count == 3) {
            end = System.currentTimeMillis();
        }
        if (count >= 3) {
            if ((end - start) < 700) {
                // 显示输入框
                Toast.makeText(this,
                        "当前Url为"+Url.ServerUrl2, Toast.LENGTH_SHORT).show();
                ll_input_url.setVisibility(View.VISIBLE);
            }
            count = 0;
        }
        if ( (System.currentTimeMillis() - start) > 1000) {
            count = 0;
            start = System.currentTimeMillis();
        }
    }

    private void setUrl() {
        String url = et_input_url.getText().toString().trim();
        if (!TextUtils.isEmpty(url)) {
            SPManage.getInstance(this).removesp();
            SPManage.getInstance(this).putCommit("WEB_URL", url);
            Url.ServerUrl2 = url;
            Toast.makeText(this,
                    "URL已改为"+Url.ServerUrl2, Toast.LENGTH_SHORT).show();
            // 重新载入 登录页面
//            startActivity(new Intent(LoginActivity.this, LoginActivity.class));
        } else {
            Toast.makeText(this,
                    "输入不能为空", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 紧急状态登录
     */
    private void urgentLogin() {
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (TextUtils.isEmpty(token)) {
            Toast.makeText(getApplicationContext(),
                    "用户token为空不能紧急登录", Toast.LENGTH_SHORT).show();
        } else {
            startAllService();

            Constatus.URGENT_TYPE = true;
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private void startAllService() {
        Intent intent = new Intent(this, GetMakemealService.class);
        startService(intent);
    }

    /**
     * 判断是否要获得url
     */
    private void isgetUrl() {
        if (!SPManage.getInstance(getApplicationContext()).getBoolen("isdeletesp")) {
            SPManage.getInstance(getApplicationContext()).removesp();
            SPManage.getInstance(getApplicationContext()).putBCommit("isdeletesp", Constatus.IS_DELETE_SP);
//            Constant.IS_DELETE_SP=false;
        }
        serverUrl = SPManage.getInstance(getApplicationContext()).getString("serverUrl");
        String serverUrlQT = SPManage.getInstance(getApplicationContext()).getString("serverUrlQT");
        if (!TextUtils.isEmpty(Url.ServerUrl2)) {
            Url.ServerUrl = Url.ServerUrl2;
            serverUrl = Url.ServerUrl2;
            SPManage.getInstance(this).putCommit("WEB_URL", serverUrl);
            return;
        }
        if (TextUtils.isEmpty(serverUrl) || TextUtils.isEmpty(serverUrlQT)) {
            getUrl();
        } else {
            Url.ServerUrl = serverUrl;
            Url.ServerUrlQT = serverUrlQT;
            Log.e("lh", "ServerUrl==" + Url.ServerUrl);
            Log.e("lh", "ServerUrlQT==" + Url.ServerUrlQT);

            //获取取餐信息
//			startAllService();
        }
    }

    private void getUrl() {
        if (errorNum >= 3) {
            return;
        }
        if (NetWorkUtil.isNetwork(getApplicationContext()) == false) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        //获得SN
        String serialNum = android.os.Build.SERIAL;
        HttpTools httptools = new HttpTools(getApplicationContext());
        httptools.getByMachine(serialNum, new JsonGetUrl());
    }

    private void login() {
        if (NetWorkUtil.isNetwork(getApplicationContext()) == false) {
            Toast.makeText(getApplicationContext(), "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        String phone = et_phone.getText().toString();
        String pwd = et_password.getText().toString();
        if (TextUtils.isEmpty(phone)) {
//            et_phone.setError("手机号为空");
            Toast.makeText(LoginActivity.this, "账号为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(LoginActivity.this, "密码为空", Toast.LENGTH_SHORT).show();
            return;
        }
        HttpTools httptools = new HttpTools(getApplicationContext());
        httptools.login(phone, pwd, "4", new JsonLogin());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 以下为副屏显示
     */
    private void initSDK() {
        mDSKernel = DSKernel.newInstance();
        mDSKernel.init(this, mConnCallback);
        showWelcomeImage();
    }

    private void checkImg(long fileId, final String key) {

        mDSKernel.checkFileExist(fileId, new ICheckFileCallback() {
            @Override
            public void onCheckFail() {
//				Toast.makeText(MainActivity.this, key + " 文件不存在", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResult(boolean b) {
                if (!b) {
                    SharedPreferencesUtil.put(LoginActivity.this, key, -1L);
                } else {
//					Toast.makeText(MainActivity.this, key + " 文件存在", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void showWelcomeImage() {
        taskId = SharedPreferencesUtil.getLong(this, WELCOME_IMG_ID);
        if (taskId != -1L) {
            showImgWelcome(taskId);
            return;
        }

        File file = new File(pathBig);
        if (!file.exists()) {
            Toast.makeText(getApplicationContext(), "No file!", Toast.LENGTH_SHORT).show();
            return;
        }
        taskId = mDSKernel.sendFile(DSKernel.getDSDPackageName(), pathBig, new ISendCallback() {
            @Override
            public void onSendSuccess(long l) {
                showImgWelcome(taskId);
                SharedPreferencesUtil.put(getApplicationContext(), WELCOME_IMG_ID, taskId);
            }

            @Override
            public void onSendFail(int i, String s) {
            }

            @Override
            public void onSendProcess(long l, long l1) {
            }
        });
    }

    private void showImgWelcome(long taskId) {
        String json1 = UPacketFactory.createJson(DataModel.SHOW_IMG_WELCOME, "");
        mDSKernel.sendCMD(DSKernel.getDSDPackageName(), json1, taskId, null);
    }

    private class JsonGetUrl extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, org.apache.http.Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            try {
                boolean code = response.getBoolean("code");
                Log.e("lh", "geturl==" + response.toString());
                if (code == true) {

                    JSONObject data = response.getJSONObject("data");
                    String name = data.getString("name");
                    String api = data.getString("api");
                    String back_url = data.getString("back_url");
                    if (!TextUtils.isEmpty(api) || !TextUtils.isEmpty(back_url)) {
                        Url.ServerUrl = back_url;
                        Url.ServerUrlQT = api;
                        Log.e("lh", "ServerUrl==" + Url.ServerUrl);
                        Log.e("lh", "ServerUrlQT==" + Url.ServerUrlQT);
                        SPManage.getInstance(getApplicationContext()).putCommit("serverUrl", back_url);
                        SPManage.getInstance(getApplicationContext()).putCommit("serverUrlQT", api);
                    }

                } else {
                    errorNum++;
                    getUrl();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
//			Toast.makeText(LoginActivity.this, "网络请求超时",
//					Toast.LENGTH_SHORT).show();
            errorNum++;
            getUrl();
        }
    }

    private class JsonLogin extends JsonHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, org.apache.http.Header[] headers,
                              JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            try {
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code == true) {
                    Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                    JSONObject data = response.getJSONObject("data");
                    Log.d("lh", data.toString());
                    String token = data.getString("token");

                    SharedPreferences spReg = getSharedPreferences("spReg",
                            Context.MODE_PRIVATE);
                    Editor editor = spReg.edit();
                    editor.putString("data", token);
                    editor.commit();

                    startAllService();

                    SharedPreferences spuser = getSharedPreferences("spuser",
                            Context.MODE_PRIVATE);
                    Editor editoruser = spuser.edit();
                    editoruser.putString("phone", et_phone.getText().toString());
					editoruser.putString("pwd", et_password.getText().toString());
                    editoruser.commit();
                    Intent intent = new Intent();
                    String address_name = null;
                    if (data.has("address_name")) {
                        address_name = data.getString("address_name");
                    }
                    intent.setClass(getApplicationContext(), MainActivity.class);
                    if (address_name != null) {
                        intent.putExtra("multi_obj_name", address_name);
                    }
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers,
                              String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Toast.makeText(LoginActivity.this, "网络请求超时",
                    Toast.LENGTH_SHORT).show();
        }

    }


}
